<template>
  <div>
    <!-- 
      show-checkbox显示复选框 
      expand-on-click-node="false"点击节点不展开
      设置node-key
      设置默认展开节点(删除后展开父节点):default-expanded-keys
    -->
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="禁用拖拽"
    >
    </el-switch>
    <el-button v-if="draggable" @click="batchSave" size="mini" type="primary"
      >批量保存</el-button
    >
    <el-button @click="batchDel" size="mini" type="danger">批量删除</el-button>
    <el-tree
      ref="menuTree"
      :draggable="draggable"
      @node-drop="handleDrop"
      :allow-drop="allowDrop"
      :data="menus"
      :props="defaultProps"
      :default-expanded-keys="expandedKeys"
      node-key="catId"
      show-checkbox
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- 叶子节点不显示添加 -->
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <!-- 有子节点不显示删除 -->
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            编辑
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [],
      maxLevel: 0,
      dialogTitle: "",
      dialogType: "", // edit / add
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: "",
      },
      menus: [],
      expandedKeys: [],
      dialogVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  activated() {
    this.getMenus();
  },
  methods: {
    batchDel() {
      let catIds = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      console.log(checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
      }
      // 发送请求删除
      this.$confirm(`是否批量删除[${catIds}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/product/category/delete"),
          method: "post",
          data: this.$http.adornData(catIds, false),
        }).then(({ data }) => {
            this.$message({
              message: "菜单批量删除成功",
              type: "success",
            })
            this.getMenus()
          })
          .catch(() => {})
      });
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单顺序修改成功",
          type: "success",
        });
        this.getMenus()
        this.expandedKeys = this.pCid;
        this.updateNodes = [];
        this.maxLevel = 0;
        // this.pCid = 0
      });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // console.log('tree drop: ', dropNode.label, dropType);
      // 1.当前节点新的父节点id
      let siblings = null;
      let pCid = 0;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);
      // 2.当前拖拽节点的最新排序
      for (let i = 0; i < siblings.length; i++) {
        // 如果遍历的是当前正在拖拽的节点
        if (siblings[i].data.catId == draggingNode.data.catId) {
          // 当前节点的默认层级
          let catLevel = draggingNode.level;
          // 如果当前节点层级发生变化
          if (siblings[i].level != catLevel) {
            // 修改当前节点层级
            catLevel = siblings[i].level;
            // 修改子节点层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      this.maxLevel = 0;

      // 3.发送请求
      // 保存功能移至batchSave()
      // console.log(this.updateNodes)
    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          let cNode = node.childNodes[i];
          cNode.catLevel = node.childNodes[i].level;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    // 拖动后总节点层级不能大于三
    allowDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      this.countNodeLevel(draggingNode);
      console.log(this.maxLevel, draggingNode.level);
      // 当前拖动的节点+父节点深度不大于3即可
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      console.log("深度: ", deep);
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      // 找到所有子节点,计算最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      } else {
        if (node.level > this.maxLevel) {
          this.maxLevel = node.level;
        }
      }
    },
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    editCategory() {
      var { catId, name, icon, productUnit } = this.category;
      var data = { catId, name, icon, productUnit };
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单修改成功",
          type: "success",
        });
        this.dialogVisible = false;
        this.getMenus();
        this.expandedKeys = [this.category.parentCid];
      });
    },
    edit(data) {
      this.dialogType = "edit";
      this.dialogTitle = "修改分类";
      // 应该查最新的数据
      // this.category.name = data.name
      // this.category.catId = data.catId
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        console.log("要回显的数据: ", data);
        this.category = data.category;
      });
      this.dialogVisible = true;
    },
    addCategory() {
      console.log("提交的三级分类数据:", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单保存成功",
          type: "success",
        });
        this.dialogVisible = false;
        this.getMenus();
        this.expandedKeys = [this.category.parentCid];
      });
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取菜单数据...", data);
        this.menus = data.data;
      });
    },
    append(data) {
      this.dialogType = "add";
      this.dialogTitle = "添加分类";
      console.log(data);
      this.dialogVisible = true;
      this.category.name = "";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
    },

    remove(node, data) {
      this.$confirm(`是否确认删除[${data.name}]?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
            // 刷新出新菜单
            this.getMenus();
            // 展开父节点
            console.log(node.parent.data.catId);
            this.expandedKeys = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style scoped>
</style>